<template>
  <el-card class="card_outsides">
    <template #header>
      <div class="card-header">
        <span>订单</span>
      </div>
    </template>

    <div class="main-content">
      <el-tabs v-model="activeTab" class="order-tabs">
        <el-tab-pane label="近3个月" name="recent" />
        <el-tab-pane label="待审核" name="pending" />
        <el-tab-pane label="待处理" name="processing" />
        <el-tab-pane label="超时预警" name="warning" />
        <el-tab-pane label="生产中" name="production" />
        <el-tab-pane label="已发货" name="shipped" />
        <el-tab-pane label="已完成" name="completed" />
        <el-tab-pane label="已关闭" name="closed" />
        <el-tab-pane label="3个月前" name="older" />
      </el-tabs>

      <div class="filter-bar">
        <div class="left-filters">
          <span class="filter-label">显示:</span>
          <el-radio-group v-model="displayFilter" class="ml-4">
            <el-radio-button label="全部" value="all" />
            <el-radio-button label="我负责的" value="mine" />
            <el-radio-button label="下属负责的" value="subordinate" />
          </el-radio-group>
        </div>
        <div class="right-actions">
          <el-button plain>清空全部条件</el-button>
          <!-- <el-button type="success" @click="handleCreate">新增</el-button> -->
          <el-button type="primary" plain @click="handleCreate">
            <Icon icon="ep:plus" class="mr-5px" />新增</el-button
          >
        </div>
      </div>

      <!-- <div class="content-area">
          <el-empty description="暂无数据" />
        </div> -->
      <el-table
        :data="orderList"
        border
        style="width: 100%"
        :header-cell-style="{ background: '#f5f7fa', color: '#606266', textAlign: 'center' }"
        :cell-style="{ textAlign: 'center' }"
      >
        <el-table-column prop="saleOrderCode" width="170" label="销售订单编号" fixed />
        <el-table-column label="下单日期" width="180" fixed>
          <template #default="{ row }">
            {{ formatCreateTime(row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="orderStatus" label="状态" fixed />
        <el-table-column prop="customerCode" label="客户编号" width="100" />
        <el-table-column prop="customerName" label="客户名称" width="90" />
        <el-table-column prop="accountManagerName" label="客户负责人" width="100" />
        <el-table-column prop="consigneeName" label="收货人" />
        <el-table-column prop="" label="产品信息" />
        <el-table-column prop="" label="销售总数量" />
        <el-table-column prop="unit" label="单位" />
        <!-- <el-table-column prop="" label="金额" />
        <el-table-column prop="" label="含税金额" />
        <el-table-column prop="" label="优惠金额" />
        <el-table-column prop="" label="优惠后金额" /> -->
        <el-table-column prop="deliveryDate" label="客户交期" width="110" />
        <el-table-column prop="shippingDate" label="出货日期" />
        <el-table-column prop="" label="预警天数" />
        <el-table-column prop="" label="逾期天数" width="100">
          <template #default="{ row }">
            <span style="color: red"> {{ calculateOverdueDays(row) }}</span>
          </template>
        </el-table-column>

        <el-table-column prop="remarks" label="备注" />
        <el-table-column prop="" label="附件" />

        <el-table-column label="操作" width="300" fixed="right">
          <template #default="{ row }">
            <el-button link type="primary" @click="handleViewDetails(row)">查看明细</el-button>
            <el-button
              link
              type="primary"
              @click="handleReviewConfirm(row)"
              v-if="row.orderStatus === '待审核'"
              >审核确认</el-button
            >
            <el-button
              link
              type="danger"
              @click="handleCloseOrder(row)"
              v-if="row.orderStatus === '待审核' || row.orderStatus === '待处理'"
              >取消订单</el-button
            >
            <el-button
              link
              type="primary"
              v-if="row.orderStatus === '待处理'"
              @click="handleBack(row)"
              >回退</el-button
            >
            <el-button
              link
              type="primary"
              v-if="row.orderStatus === '待处理'"
              @click="handlePush(row)"
              >下推</el-button
            >
            <el-button
              link
              type="primary"
              v-if="
                row.orderStatus === '检测完成' ||
                row.orderStatus === '已完成' ||
                row.orderStatus === '检测完成'
              "
              >查看质量报告</el-button
            >
            <el-button
              type="primary"
              link
              @click="handleEdit(row)"
              v-if="row.orderStatus === '待审核'"
            >
              编辑
            </el-button>
            <el-button
              type="danger"
              link
              v-if="row.orderStatus === '已完成' || row.orderStatus === '已关闭'"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        class="pagination"
        :current-page="currentPage"
        :page-size="pageSize"
        :total="total"
        layout="prev, pager, next, jumper, ->, slot"
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange"
      >
        <div class="footer-bar">
          <el-tag type="success" size="large" effect="light" class="order-count-tag">
            订单数 {{ total }}
          </el-tag>
          <el-button :icon="MoreFilled" circle />
        </div>
      </el-pagination>
    </div>
    <OrderFormModal
      v-model:visible="isModalVisible"
      :title-flag="flag"
      :initial-data="selectedOrder"
      @submit="handleFormSubmit"
    />
    <OrderDetailModal v-model:visible="detailModalVisible" :initial-data="currentOrderDetail" />
  </el-card>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { MoreFilled } from '@element-plus/icons-vue'
import { OrderVO } from '@/api/order'
import OrderFormModal from './OrderFormModal.vue'
import { OrderApi } from '@/api/order'
import { ElMessage } from 'element-plus'
import dayjs from 'dayjs'
import OrderDetailModal from './OrderDetailModal.vue'
import { constant } from 'lodash-es'

const currentPage = ref(1) // 当前页码
const pageSize = ref(10) // 每页显示数量
const total = ref(0) // 总记录数

// 控制弹窗是否显示
const isModalVisible = ref(false)
const detailModalVisible = ref(false)
// 存储当前正在编辑的订单数据，如果是新增，则为 null
const selectedOrder = ref<OrderVO | null>(null)
// 存储当前要查看的订单的详细数据
const currentOrderDetail = ref(null)

const orderList = ref<OrderVO[]>([])
// 当前激活的Tab
const activeTab = ref('recent')
// 当前激活的显示过滤器
const displayFilter = ref('all')
const flag = ref('add')

const loadOrderList = async () => {
  const res = await OrderApi.getOrderPage({
    pageNo: currentPage.value, // 当前页码
    pageSize: pageSize.value,
    tags: activeTab.value // 每页数量
  })
  orderList.value = res.list || [] // 更新当前页数据
  total.value = res.total || 0 // 更新总记录数
}

const formatCreateTime = (timestamp: number) => {
  if (!timestamp) return '' // 时间戳不存在时返回空字符串
  return dayjs(timestamp).format('YYYY-MM-DD HH:mm:ss') // 格式化为 "2024-03-15 14:30:25"
}

onMounted(loadOrderList) // 组件挂载时加载数据

/**
 * 处理创建新订单
 */
const handleCreate = () => {
  // 将 selectedOrder 设为 null，弹窗会识别为“新增”模式
  selectedOrder.value = null
  // 打开弹窗
  flag.value = 'add'
  isModalVisible.value = true
}

/**
 * 处理编辑订单
 */
const handleEdit = async (order: OrderVO) => {
  // 将选中的订单数据赋值给 selectedOrder，弹窗会用此数据填充表单
  try {
    // 调用 getOrder 接口获取最新订单详情
    const orderDetail = await OrderApi.getOrder(order.id!) // ! 表示断言 id 非空（根据业务逻辑确保）
    selectedOrder.value = orderDetail // 将接口返回的详情赋值给 selectedOrder
    flag.value = 'edit'
    isModalVisible.value = true // 打开弹窗
  } catch (error) {
    ElMessage.error('获取订单详情失败，请重试')
  }

  isModalVisible.value = true
}

// --- 新增分页事件处理 ---
const handleCurrentChange = (newPage: number) => {
  currentPage.value = newPage
  loadOrderList() // 页码变化时重新加载数据
}

const handleSizeChange = (newSize: number) => {
  pageSize.value = newSize
  currentPage.value = 1 // 切换每页数量时重置为第一页
  loadOrderList() // 重新加载数据
}
const handleReviewConfirm = async (order: OrderVO) => {
  try {
    // 调用 getOrder 接口获取最新订单详情
    await OrderApi.checkOrder(order.id!) // ! 表示断言 id 非空（根据业务逻辑确保）
    ElMessage.success('审核确认成功')
    loadOrderList()
  } catch (error) {
    ElMessage.error('审核确认失败，请重试')
  }
}
/**
 * 处理弹窗提交事件
 * @param formData - 从弹窗传回的表单数据
 * @param fileList - 从弹窗传回的文件列表
 */
const handleFormSubmit = async (formData: OrderVO, fileList: any[]) => {
  try {
    if (formData.id) {
      // 编辑操作：调用 updateOrder
      await OrderApi.updateOrder(formData)
      ElMessage.success('更新成功')
    } else {
      // 新增操作：调用 createOrder
      await OrderApi.createOrder(formData)
      ElMessage.success('创建成功')
    }
    isModalVisible.value = false // 关闭弹窗
    loadOrderList() // 刷新订单列表
  } catch (error) {
    ElMessage.error('提交失败')
  }
}
watch(activeTab, (newTab) => {
  currentPage.value = 1 // 切换标签时重置为第一页
  loadOrderList() // 重新加载数据
})

const handleViewDetails = async (order) => {
  try {
    // 调用您已有的后端接口获取订单详情
    const detailData = await OrderApi.getOrder(order.id)

    // 将获取到的数据存起来
    currentOrderDetail.value = detailData

    // 打开弹窗
    detailModalVisible.value = true
  } catch (error) {
    console.error('获取订单详情失败:', error)
    // 这里可以加一个错误提示，例如 ElMessage.error
  }
}

const handleCloseOrder = async (order) => {
  try {
    // 调用您已有的后端接口关闭订单
    await OrderApi.closeOrder(order.id)

    // 刷新订单列表
    loadOrderList()
    ElMessage.success('关闭订单成功')
  } catch (error) {
    console.error('关闭订单失败:', error)
    // 这里可以加一个错误提示，例如 ElMessage.error
  }
}

const handleBack = async (order) => {
  try {
    // 调用您已有的后端接口关闭订单
    await OrderApi.backOrder(order.id)

    // 刷新订单列表
    loadOrderList()
    ElMessage.success('回退订单成功')
  } catch (error) {
    console.error('回退订单失败:', error)
  }
}

const handlePush = async (order) => {
  try {
    // 调用您已有的后端接口关闭订单
    await OrderApi.pushOrder(order.id)

    // 刷新订单列表
    loadOrderList()
    ElMessage.success('下推订单成功')
  } catch (error) {
    console.error('下推订单失败:', error)
  }
}

const calculateOverdueDays = (order) => {
  if (!['生产中', '检测完成'].includes(order.orderStatus)) {
    return ''
  }
  if (!order.deliveryDate) return ''
  const deliveryDate = dayjs(order.deliveryDate)
  const currentDate = dayjs()
  const overdueDays = currentDate.diff(deliveryDate, 'day')
  const text = '已逾期'
  return overdueDays > 0 ? text + overdueDays + '天' : ''
}
</script>

<style scoped>
.order-tabs {
  /* 自定义 el-tabs 激活状态下的下划线颜色 */
  --el-tabs-header-height: 50px;
}

.order-tabs :deep(.el-tabs__item.is-active) {
  color: var(--el-color-success);
}

.order-tabs :deep(.el-tabs__active-bar) {
  background-color: var(--el-color-success);
}

.order-tabs :deep(.el-tabs__item:hover) {
  color: var(--el-color-success-light-3);
}

.filter-bar {
  display: flex;
  padding: 15px;
  background-color: #fcfcfc;
  border-radius: 4px;
  justify-content: space-between;
  align-items: center;
}

.left-filters {
  display: flex;
  align-items: center;
}

.filter-label {
  margin-right: 16px;
  font-size: 14px;
  color: #606266;
}

/* 自定义 el-radio-button 激活状态下的样式 */
:deep(.el-radio-button__original-radio:checked + .el-radio-button__inner) {
  color: var(--el-color-white);
  background-color: var(--el-color-success);
  border-color: var(--el-color-success);
  box-shadow: -1px 0 0 0 var(--el-color-success);
}

:deep(.el-radio-button__inner:hover) {
  color: var(--el-color-success);
}

.right-actions .el-button.is-link {
  font-size: 14px;
}

.content-area {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 400px; /* 根据实际需要调整高度 */
  padding: 20px 0;
}

.footer-bar {
  display: flex;
  padding: 15px 20px;
  background-color: #fff;
  border-top: 1px solid #e4e7ed;
  justify-content: flex-end;
  align-items: center;
}

.order-count-tag {
  height: 32px;
  padding: 0 15px;
  margin-right: 12px;
  font-size: 14px;
  line-height: 32px;

  /* 自定义 el-tag 样式使其更接近图片效果 */
  color: #67c23a;
  background-color: #f0f9eb;
  border: none;
  border-radius: 4px; /* 图片中是圆角矩形 */
}
</style>
